﻿using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Rob.SampleCode.NHibernate.Core;
using Rob.SampleCode.NHibernate.Infrastructure;
using StructureMap;
using StructureMap.ServiceLocatorAdapter;

namespace Rob.SampleCode.NHibernate.UI
{
    public class MvcApplication : HttpApplication
    {
        private static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        private static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapRoute("Default", "{controller}/{action}/{id}", new {controller = "Home", action = "Index", id = UrlParameter.Optional});
        }

        private static void InitializeIoc()
        {
            ObjectFactory.Initialize(x =>
            {
                x.For<NHibernateUnitOfWork>().HybridHttpOrThreadLocalScoped().Use<NHibernateUnitOfWork>();
                x.For<IRepository>().Use<NHibernateRepository>();
                x.Scan(scanner =>
                {
                    scanner.Assembly("Rob.SampleCode.NHibernate.Core");
                    scanner.Assembly("Rob.SampleCode.NHibernate.Infrastructure");
                    scanner.Assembly("Rob.SampleCode.NHibernate.UI");
                    scanner.WithDefaultConventions();
                });
            });

            Ioc.Initialize(new StructureMapServiceLocator(ObjectFactory.Container));
        }

        protected void Application_Start()
        {
            InitializeIoc();

            DependencyResolver.SetResolver(Ioc.CurrentLocator);
            AreaRegistration.RegisterAllAreas();
            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
        }

        protected void Application_EndRequest(object sender, EventArgs e)
        {
            Ioc.Resolve<NHibernateUnitOfWork>().End();
        }
    }
}